package com.game.framwork.gamesupport;

import android.graphics.Point;
import android.graphics.Rect;

import com.game.framwork.itf.Graphics;
import com.game.framwork.itf.Pixmap;

public class GameSprite {
	private Pixmap image;
	private String strName;
	private int id;

	public int currFrame;
	public int startFrame;
	public int endFrame;
	public int loopFrame;
	public int currIndex;

	private float actionSpeed;
	private float localTime;

	private int[] listFrame;

	private boolean isReverse;
	private boolean isSequence;

	public GameSprite(Pixmap image) {
		this.image = image;
		currFrame = 0;
		startFrame = 0;
		endFrame = 0;
		loopFrame = 0;
		actionSpeed = 0.0f;
		localTime = 0.0f;
		isReverse = false;
		listFrame = null;
		isSequence = false;
		currIndex = 0;
	}

	public void createAnimation(String name, int startFrame, int endFrame,
			int loopFrame, float actionSpeed) {
		strName = name;
		this.startFrame = startFrame;
		this.endFrame = endFrame;
		this.loopFrame = loopFrame;
		this.actionSpeed = actionSpeed;
		this.currFrame = startFrame;
	}

	public void updateSourceRect(Rect sourceRect, int width, int height,
			int numFrameInRow) {
		sourceRect.left = (currFrame % numFrameInRow) * width;
		sourceRect.top = (currFrame / numFrameInRow) * height;
		sourceRect.right = sourceRect.left + width + 1;
		sourceRect.bottom = sourceRect.top + height + 1;
	}

	public void update(float deltaTime, Rect sourceRect, int width, int height,
			int numFrameInRow) {
		localTime += deltaTime;
		if (localTime >= actionSpeed) {
			if (!isSequence) // if normal
			{
				if (!isReverse) {// if we update animation forward
					nextFrame();
				} else {
					// if we update animation backward
					previousFrame();
				}
			} else {// if we update animation base on sequence frame
				currFrame = listFrame[currFrame];
				currFrame += 1;
				if (currFrame >= listFrame.length)
					currFrame = 0;
			}
			updateSourceRect(sourceRect, width, height, numFrameInRow);
			localTime -= actionSpeed;
		}
	}

	private void nextFrame() {
		currFrame += 1;
		if (currFrame > endFrame)
			currFrame = loopFrame;
	}

	private void previousFrame() {
		currFrame -= 1;
		if (currFrame < startFrame)
			currFrame = 0;
	}

	public void paint(Graphics g, Point pos, Rect recSource) {
		g.drawPixmap(image, pos.x, pos.y, recSource.left, recSource.top,
				recSource.right - recSource.left, recSource.bottom
						- recSource.top);
	}

	public boolean isEndAnimation() {
		if (currFrame == endFrame)
			return true;

		return false;
	}

	public void resetAnimation() {
		currFrame = startFrame;
	}

	public String getSpriteName() {
		return strName;
	}

	public int getSpriteId() {
		return id;
	}
}
